package com.ksc.storekeeper.client.view.impl;

import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;
import com.ksc.storekeeper.client.view.AddUserView;
import com.ksc.storekeeper.client.view.components.FormItemPasswordBox;
import com.ksc.storekeeper.client.view.components.FormItemTextBox;
import com.ksc.storekeeper.shared.dto.UserDTO;

public class AddUserViewImpl extends ViewImpl implements AddUserView {

	private final Widget widget;
	private final AddUserViewUiBinder uiBinder = GWT.create(AddUserViewUiBinder.class);
	private AddUserUiHandler uiHandler;

	@UiField
	Button addUser;
	
	@UiField
	FormItemTextBox username;
	
	@UiField
	FormItemPasswordBox password;
	
	@UiField
	FormItemPasswordBox confirmPassword;
	
	@UiField
	HTML infoMsg;

	interface AddUserViewUiBinder extends UiBinder<Widget, AddUserViewImpl> {

	}

	public AddUserViewImpl() {
		widget = uiBinder.createAndBindUi(this);
	}

	@UiHandler("addUser")
	public void onAddButtonClicked(final ClickEvent event) {
		if(validate()) {
			String uname=username.getText();
			String pass=password.getText();
			String confirm=confirmPassword.getText();
			if(!pass.equals(confirm)) {
				infoMsg.setText("Password don't match");
			}
			else {
			UserDTO newUser = new UserDTO();
			newUser.setUserName(uname);
			newUser.setPassword(pass);
			uiHandler.addUser(newUser);
			}
		}
	}
	
	private boolean validate() {
		boolean valid=username.validate() & password.validate() & confirmPassword.validate();
		return valid;
	}

	@Override
	public Widget asWidget() {
		return this.widget;
	}

	@Override
	public void setUiHandlers(AddUserUiHandler uiHandlers) {
		this.uiHandler = uiHandlers;
	}

}
